﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FtpLib;
using System.Configuration;
using RPSImporter.Models.Importers;
using System.IO;
using System.Net;
using System.Threading;
using RPSImporter.Models;
using RPSImporter.Models.Settings;

namespace RPSImporter.Services
{
    public class FtpSvc
    {
        #region Singleton
        static FtpSvc instance = null;

        FtpSvc()
        { }

        public static FtpSvc Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new FtpSvc();
                }
                return instance;
            }
        }
        #endregion

        private FtpConnection Connection { get; set; }

        public string Error { get; set; }

        private bool Connect()
        {
            GeneralSettings currentSettings = DatabaseSvc.Instance.Settings.GeneralSettings.FirstOrDefault();

            this.Connection = new FtpConnection(
               currentSettings.FtpAddress,
               currentSettings.FtpUsername,
               currentSettings.FtpPassword);

            try
            {
                this.Connection.Open();
                this.Connection.Login();
                return true;
            }
            catch (Exception)
            {
                this.Error = "Impossible de se connecter au serveur FTP! S'il vous plaît vérifier vos paramètres et réessayez.";
                return false;
            }
        }

        public void Import()
        {
            if (!this.Connect()) return;

            GeneralSettings currentSettings = DatabaseSvc.Instance.Settings.GeneralSettings.FirstOrDefault();

            this.Connection.SetCurrentDirectory(currentSettings.FtpPath);
            FtpFileInfo[] files = this.Connection.GetFiles("*.csv")
                                       .Union(this.Connection.GetFiles("*.xls"))
                                       .Union(this.Connection.GetFiles("*.xml")).ToArray();

            foreach (var file in files)
            {
                string localFilePath = String.Format(@"{0}\{1}", ConfigurationManager.AppSettings["ImportPath"], file.Name);
                File.Delete(localFilePath);

                this.Connection.GetFile(file.Name, localFilePath, false);
                this.Connection.Close();
                this.Connection.Dispose();

                var importer = ImporterFactory.Instance.GetImporter(localFilePath);
                if (importer != null)
                {
                    importer.Import();
                }
            }

        }
    }
}